﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using PS.Practices.Provisioner.Provisioner;
using PS.Practices.Provisioner.Provisioner.Util;

namespace PS.Practices.Provisioner.Sandbox.Util
{
    public class SandboxProvisionerLogger : ISandboxLogger, IDisposable
    {
        private List<string> LogItems { get; set; }
        private SPWeb Web { get; set; }
        private bool Successed { get; set; }
        
        public SandboxProvisionerLogger(SPWeb spWeb)
        {
            if (spWeb == null) throw new ArgumentNullException("spWeb");
            Web = spWeb;
            Successed = true;
            LogItems = new List<string>();
        }

        public void Info(string message)
        {
            if (message == null) throw new ArgumentNullException("message");
            LogItems.Add(string.Format("Info: {0}", message));
        }

        public void Error(Exception spException)
        {
            if (spException == null) throw new ArgumentNullException("spException");
            Successed = false;
            LogItems.Add(string.Format("Error: {0}", spException.Message));
        }

        public void Error(string messageFormat, params object[] args)
        {
            if (messageFormat == null) throw new ArgumentNullException("messageFormat");
            if (args == null) throw new ArgumentNullException("args");
            Successed = false;
            LogItems.Add(string.Format(messageFormat, args));
        }

        public void Dispose()
        {
            FlushLogItems();
        }

        private void FlushLogItems()
        {
            if (LogItems.Count == 0) return;

            string webTitle = Web.Title;
            DateTime created = Web.Created;

            SPWeb rootWeb = Web.Site.RootWeb;
            string listUrl = rootWeb.ServerRelativeUrl == "/"
                    ? Constants.ProvisionerLoggerListUrl
                    : rootWeb.ServerRelativeUrl + Constants.ProvisionerLoggerListUrl;
            try
            {
                SPList spList = rootWeb.GetList(listUrl);
                SPListItemCollection listItems = spList.Items;
                if(listItems.Count > Constants.LogItemCountLimit)
                {
                    listItems[0].Delete();
                }
                SPListItem item = listItems.Add();
                item["Title"] = webTitle;
                item["WebCreated"] = created;
                item["Log"] = GetLogText();
                item["Status"] = Successed ? "Success" : "Error";
                item.Update();
            }
            catch
            {
            }
        }

        private string GetLogText()
        {
            var sb = new StringBuilder();
            foreach (var logItem in LogItems)
            {
                //sb.Append(string.Format("{0} <br/>", logItem));
                sb.AppendLine(logItem);
            }
            return sb.ToString();
        }
    }
}
